/*
 * Copyright (c) 2011-2014 BlackBerry Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/cascades/LocaleHandler>
#include <bb/cascades/maps/MapView>
#include <bb/system/SystemDialog>
#include <bb/UIToolkitSupport>
#include <QtLocationSubset/QGeoServiceProvider>

#include "applicationui.hpp"
#include "LocationHandler.hpp"
#include "security/System.hpp"
#include "security/Session.hpp"
#include "network/Manager.hpp"
#include "user/UserManager.hpp"
#include "user/ContactManager.hpp"



using namespace bb::cascades;
using namespace bb::pim::contacts;
using namespace bb::cascades::maps;
using namespace bb::platform::geo;
using namespace QtMobilitySubset;
using namespace de::heimweghelden;

ApplicationUI::ApplicationUI() :
        QObject(),
        _locationHandler(new de::heimweghelden::LocationHandler(this)),
        _contactManager(new de::heimweghelden::user::ContactManager(this)),
        _networkmanager(new QNetworkAccessManager(this))
{
    qmlRegisterType<LocationHandler>("de.heimweghelden", 1, 0, "LocationHandler");


    appStatus = 0;
    de::heimweghelden::network::Manager::getInstance(this);
    de::heimweghelden::user::UserManager::getInstance(this);
    de::heimweghelden::security::System::getInstance();
    /*
    de::heimweghelden::security::Session *session = de::heimweghelden::security::System::getInstance()->createSession();
    if (session != NULL) {
        QString aesEnc = session->encrypt("Ich heisse Chandra!");
        qDebug() << "createSession()->encrypt" << aesEnc;
        QString aesDec = session->decrypt(aesEnc);
        qDebug() << "createSession()->decrypt" << aesDec;
    }
    */


    // prepare the localization
    m_pTranslator = new QTranslator(this);
    m_pLocaleHandler = new LocaleHandler(this);

    bool res = QObject::connect(m_pLocaleHandler, SIGNAL(systemLanguageChanged()), this, SLOT(onSystemLanguageChanged()));
    // This is only available in Debug builds
    Q_ASSERT(res);
    // Since the variable is not used in the app, this is added to avoid a
    // compiler warning
    Q_UNUSED(res);

    // initial load
    onSystemLanguageChanged();

    // Create scene document from main.qml asset, the parent is set
    // to ensure the document gets destroyed properly at shut down.
    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    qml->setContextProperty("app", this);
    qml->setContextProperty("locationHandler", this->locationHandler());
    qml->setContextProperty("contactManager", this->contactManager());

    // Create root object for the UI
    AbstractPane *root = qml->createRootObject<AbstractPane>();

    // bin mapView to locationHandler
    QObject* mapViewAsQObject = root->findChild<QObject*>(QString("mapViewObj"));
    if (mapViewAsQObject) {
        mapView = qobject_cast<bb::cascades::maps::MapView*>(mapViewAsQObject);
        if (mapView) {
            locationHandler()->setMap(mapView);
        }
    }




    // Set created root object as the application scene
    Application::instance()->setScene(root);

    // find contacts data model
    /*QObject* contactsModel = root->findChild<QObject*>(QString("contactsModel"));
    if (contactsModel) {
        qDebug() << "contactModel wurde gefunden";
        bb::cascades::GroupDataModel* c = qobject_cast<bb::cascades::GroupDataModel*>(contactsModel);
        if (c) {
            _contactManager->bindModel(c);
        }
    } else {
       qDebug() << "contactModel NICHT gefunden!";
    }*/
}

ApplicationUI::~ApplicationUI() {
    de::heimweghelden::user::UserManager::drop();
    de::heimweghelden::network::Manager::drop();
    de::heimweghelden::security::System::drop();
}

void ApplicationUI::onSystemLanguageChanged()
{
    QCoreApplication::instance()->removeTranslator(m_pTranslator);
    // Initiate, load and install the application translation files.
    QString locale_string = QLocale().name();
    QString file_name = QString("HeimwegHelden_%1").arg(locale_string);
    if (m_pTranslator->load(file_name, "app/native/qm")) {
        QCoreApplication::instance()->installTranslator(m_pTranslator);
    }
}
void ApplicationUI::changeAppStatus(int status) {
    appStatus = status;
    emit onAppStatusChanged(status);
}




void ApplicationUI::alert(const QString &message, bool fatal)
{
    //TODO: wenn der fehler fatal ist, muss die application geschlossen werden
    bb::system::SystemDialog* dialog; // SystemDialog uses the BB10 native dialog.
    dialog = new bb::system::SystemDialog(tr("OK"), 0); // New dialog with on 'Ok' button, no 'Cancel' button
    dialog->setTitle(tr(fatal ? "Fatal Error!": "Warning")); // set a title for the message
    dialog->setBody(message); // set the message itself
    dialog->setDismissAutomatically(true); // Hides the dialog when a button is pressed.

    // Setup slot to mark the dialog for deletion in the next event loop after the dialog has been accepted.
    bool ok = connect(dialog, SIGNAL(finished(bb::system::SystemUiResult::Type)), dialog, SLOT(deleteLater()));
    Q_ASSERT(ok);
    Q_UNUSED(ok);
    dialog->show();
}
